package com.power.sifa.approve.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.core.base.model.Ha_attachment;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.approve.dao.Apl_arrive_materialDao;
import com.power.sifa.approve.model.Apl_arrive_material;
import com.power.sifa.approve.model.pageInfo.Apl_arrive_materialPageInfo;
import com.power.sifa.approve.service.Apl_arrive_materialService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 *  送达记录文书材料业务层实现
 */
@Service
public class Apl_arrive_materialServiceImpl extends BaseServiceImpl implements Apl_arrive_materialService {

    @Autowired
    private Apl_arrive_materialDao dao;

    @Autowired
    private Ha_attachmentService ha_attachmentService;


    @Override
    public Apl_arrive_material getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Apl_arrive_material apl_arrive_material) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (apl_arrive_material.getPrimaryKey() != null) {
        	 Apl_arrive_material apl_arrive_materialfDb = dao.findById(apl_arrive_material.getPrimaryKey()).orElse(null);
             if(apl_arrive_materialfDb != null) {
                BeanUtils.copyProperties(apl_arrive_material, apl_arrive_materialfDb);
                dao.save(apl_arrive_materialfDb);
                return;
             }
        }
        dao.save(apl_arrive_material);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Apl_arrive_material> findAll(Apl_arrive_materialPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }
    
    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }
    
    @Override
	public List<Apl_arrive_material> findAll() {
		return dao.findAll();
	}
	
	@Override
	public void saveAll(List<Apl_arrive_material> list) {
		dao.saveAll(list);
	}

    @Override
    public List<Apl_arrive_material> findMaterialsByRecordIds(List<String> recordIds) {
        List<Apl_arrive_material> materials = dao.findMaterialsByRecordIds(recordIds);
        if (CollUtil.isNotEmpty(materials)) {
            materials.stream().forEach(material -> material.geneText());
            List<String> attachementIds = materials.stream().map(Apl_arrive_material::getAttachid).collect(Collectors.toList());
            Map<String, Ha_attachment> ha_attachmentMap = ha_attachmentService.getHa_attachmentsByIds(attachementIds);
            if (ObjectUtil.isNotNull(ha_attachmentMap)) {
                materials.stream().forEach(m -> {
                    Optional.ofNullable(ha_attachmentMap.get(m.getAttachid())).ifPresent(then -> {
                        m.setFile(ha_attachmentMap.get(m.getAttachid()));
                    });
                });
            }
            return materials;
        }
        return Collections.emptyList();
    }

    @Override
    public void removeByRecordIds(List<String> recordIds) {
        dao.removeByRecordIds(recordIds);
    }
}
